import os
import numpy as np
from PIL import Image

def Image2Jpeg(pathin,pathout,imagename):
    #判断输出路径是否存在
    isExists=os.path.exists(pathout)
    if not isExists:
        os.mkdir(pathout)
    
    #以二进制格式读取文件
    f = open(file=pathin,mode='rb')
    data = f.read()
    #空过文件前a行
    a=3181
    
    #创建两个数组分别存储两帧图像数据
    Im_1=np.zeros((pixle_y,pixle_x)) 
    Im_2=np.zeros((pixle_y,pixle_x)) 
    for j in range(pixle_y):
        for i in range(pixle_x):
            index1 = a+i*pixle_y*2+j*2
            Im_1[pixle_y-j-1][i]=int(str(bin(data[index1+1]))+str(bin(data[index1])[2:].zfill(8)),2)
            
    for j in range(pixle_y):
        for i in range(pixle_x):
            index2 = a+pixle_x*pixle_y*2+i*pixle_y*2+j*2
            Im_2[pixle_y-j-1][i]=int(str(bin(data[index2+1]))+str(bin(data[index2])[2:].zfill(8)),2)
    
    #将矩阵按照图片格式写出
    image = Image.fromarray(Im_1)
    if image.mode == "F":
        image = image.convert('RGB') 
    image.save(os.path.join(pathout,imagename+'_1.jpeg'))
    
    image = Image.fromarray(Im_2)
    if image.mode == "F":
        image = image.convert('RGB') 
    image.save(os.path.join(pathout,imagename+'_2.jpeg'))
    
    f.close()
    return 0

if __name__=="__main__":
    #图像的像素大小
    pixle_x = 2048
    pixle_y = 1548
    
    #image文件的文件名，确定输入和出路径
    imagename = 'image#1'
    pathin = os.path.join(r'C:\Users\HWW\Desktop\data', imagename +'.image')
    pathout = r'C:\Users\HWW\Desktop\data\Image'
    Image2Jpeg(pathin,pathout,imagename)

